import { Button, Space } from 'antd';
import { useEffect, useState, useMemo, useRef } from 'react';
import { getSubjects, getPositions } from 'api/dictionary';
import { search, UpdatePassword, UpdateTeacher, AddTeacher, UpdateStatus, ChangeRoles } from 'api/teacher';
import { getList, getTeacherRoles } from 'api/roles';
import { NavLink } from 'react-router-dom';
import menuStore from 'store/menu';
import Table from 'com/Table';
import Form from 'com/Form';
import Modal from 'com/Modal';
import MF from 'com/ModalForm';
import dayjs from 'dayjs';

/**
 * 修改密码表单配置项
 */
const passwordOptions = {
    password: {
        title: '新密码',
        max: 20,
        required: true,
        type: 'password',
        rules: [{ pattern: /^[\da-zA-Z-_+=]{6,20}$/, message: '新密码必须为数字、字母或-_+=的组合，并且6-20位' }]
    },
    confirmPassword: {
        title: '确认密码',
        max: 20,
        type: 'password',
        required: true,
        rules: [{ pattern: /^[\da-zA-Z-_+=]{6,20}$/, message: '确认密码必须为数字、字母或-_+=的组合，并且6-20位' },
        {
            match: 'password', message: '确认密码和新密码不一致'
        }]
    }
}

/**
 * 教师列表
 */
export default () => {
    const [list, setList] = useState([]);
    /**
     * 角色列表
     */
    const [roles, setRoles] = useState([]);
    /**
     * loading
     */
    const [loading, setLoading] = useState(false);
    /**
     * 总条数
     */
    const [total, setTotal] = useState(0);
    /**
     * 角色默认值
     */
    const [roleValues, setRoleValues] = useState({});
    /**
     * Modal引用
     */
    const modal = useRef();
    /**
     * 当前要修改的teacher数据
     */
    const [teacher, setTeacher] = useState({});
    /**
     * form引用
     */
    const form = useRef();
    /**
     * 修改状态的MF引用
     */
    const statusMF = useRef();
    /**
     * 变更橘色的MF引用
     */
    const roleMF = useRef();
    /**
     * ModalForm引用
     */
    const mf = useRef();
    /**
     * 查询数据
     */
    const [searchModel, setSearchModel] = useState({
        subject: 0,
        pageNo: 1,
        pageSize: 10
    });
    /**
     * 科目列表
     */
    const [subjects, setSubjects] = useState([{ label: '所有', value: 0 }]);
    /**
     * 职称
     */
    const [positions, setPositions] = useState([]);
    /**
     * 表单配置项
     */
    const options = useMemo(() => ({
        ...(menuStore.auth('teacherList') ? {
            name: {
                title: '教师姓名',
                max: 20,
            },
            idNo: {
                title: '身份证号',
                max: 18,
            },
            phone: {
                title: '手机号',
                max: 11
            },
            subject: {
                tag: 'select',
                title: '科目',
                style: { minWidth: 100 },
                values: subjects
            },
            button: {
                tag: 'button',
                text: '搜索',
                loading,
                htmlType: 'submit'
            }
        } : {})
        ,
        ...(menuStore.auth('addTeacher') ? {
            add: {
                tag: 'button',
                text: '添加教师',
                click: () => {
                    setTeacher({});
                    mf.current.show();
                }
            }
        } : {})
    }), [loading, subjects]);
    /**
       * 修改基本信息
       */
    const updateOptions = useMemo(() => {
        const [a, ...rest] = subjects;
        return {
            ...(teacher.id ? {} : {
                username: {
                    title: '用户名',
                    required: true,
                    min: 2,
                    max: 20
                },
                password: {
                    title: '密码',
                    type: 'password',
                    required: true,
                    rules: [{ pattern: /^[\da-zA-Z-_+=]{6,20}$/, message: '密码必须为6-20位数字、字母或-_+=的组合' }]
                }
            }),
            name: {
                title: '教师姓名',
                required: true,
                max: 20,
                min: 2
            },
            work_no: {
                tag: 'number',
                title: '工号',
                required: true,
                attrs: { min: 1000000, max: 9999999 },
                style: { width: '100%' },
            },
            salary: {
                tag: 'number',
                title: '薪资',
                required: true,
                attrs: { min: 1000, max: 9999999 },
                style: { width: '100%' },
            },
            position: {
                tag: 'select',
                title: '职称',
                required: true,
                values: positions
            },
            idNo: {
                title: '身份证号',
                required: true,
                max: 18,
                rules: [{ pattern: /^\d{17}[\dXx]$/, message: '身份证号格式不正确' }]
            },
            phone: {
                title: '手机号',
                required: true,
                max: 11,
                rules: [{ pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }]
            },
            address: {
                title: '地址',
                required: true,
                max: 100,
                min: 10
            },
            subject: {
                tag: 'select',
                title: '科目',
                required: true,
                values: rest
            },
        }
    }, [subjects, positions, teacher])
    /**
     * 变更角色表单配置项
     */
    const roleOptions = useMemo(() => ({
        roleIds: {
            title: '角色',
            required: true,
            tag: 'select',
            attrs: { mode: 'multiple' },
            values: roles
        }
    }), [roles]);
    /**
     * 列定义
     */
    const cols = [{
        title: '用户名',
        dataIndex: 'username',
        align: 'center'
    },
    {
        title: '姓名',
        dataIndex: 'name',
        align: 'center'
    },
    {
        title: '性别',
        dataIndex: 'sex',
        align: 'center'
    },
    {
        title: '工号',
        dataIndex: 'work_no',
        align: 'center'
    },
    {
        title: '身份证号',
        dataIndex: 'idNo',
        align: 'center'
    },
    {
        title: '手机号',
        dataIndex: 'phone',
        align: 'center'
    },
    {
        title: '薪资',
        dataIndex: 'salary',
        align: 'center'
    },
    {
        title: '职称',
        dataIndex: ['p', 'name'],
        align: 'center'
    },
    {
        title: '科目',
        dataIndex: ['s', 'name'],
        align: 'center'
    },
    {
        title: '地址',
        dataIndex: 'address',
        align: 'center'
    },
    {
        title: '状态',
        dataIndex: 'status',
        render: text => text ? '在职' : '已离职',
        align: 'center'
    },
    {
        title: '操作',
        align: 'center',
        width: 150,
        render: (text, row) => <Space>
            {
                menuStore.auth('updateTeacher') && <Button type="link" size="small" onClick={() => {
                    setTeacher({ ...row });
                    mf.current.show();
                }}>修改基本信息</Button>
            }
            {
                menuStore.auth('changeTeacherStatus') && <Button type="link" size="small" onClick={() => {
                    setTeacher({ ...row });
                    statusMF.current.show();
                }}>变更状态</Button>
            }
            {
                menuStore.auth('updateTeacherPassword') && <Button type="link" size="small" onClick={() => {
                    setTeacher({ ...row });
                    modal.current.show();
                }}>修改密码</Button>
            }
            {
                menuStore.auth('addTeacherRoles') && <Button type="link" size="small" onClick={() => openChangeRoles(row)}>变更角色</Button>
            }
            {
                menuStore.auth('emergency', 'addEmergency') && <NavLink style={{ whiteSpace: 'nowrap' }} to={"/emergency/" + row.id}>紧急联系人管理</NavLink>
            }
        </Space>
    }
    ];

    (menuStore.auth('addTeacher') || (menuStore.all('teacherList', 'updateTeacher'))) && useEffect(() => {
        const getList = async () => {
            try {
                const list = await getSubjects();
                setSubjects([{ label: '所有', value: 0 }, ...list.map(item => ({ label: item.name, value: item.id }))]);
            } catch (error) { }
        }
        const getPositionList = async () => {
            try {
                const list = await getPositions();
                setPositions(list.map(c => ({ label: c.name, value: c.id })));
            } catch (error) { }
        }
        getList();
        getPositionList();
    }, []);

    menuStore.all('teacherList', 'addTeacherRoles') && useEffect(() => {
        const getRoles = async () => {
            try {
                const list = await getList();
                setRoles(list.map(c => ({ label: c.name, value: c.id })));
            } catch (error) {
                console.log(error);
            }
        }
        getRoles();
    }, []);

    menuStore.auth('teacherList') && useEffect(() => {
        /**
        * 搜索
        */
        const searchList = async () => {
            try {
                setLoading(true);
                const { data, total } = await search(searchModel);
                setList(data);
                setTotal(total);
            } catch (error) { }
            setLoading(false);
        }
        searchList();
    }, [searchModel]);

    /**
     * 修改密码
     * @param {*} values 
     */
    const updatePassword = async (values) => {
        try {
            modal.current.start();
            await UpdatePassword({ id: teacher.id, ...values });
            modal.current.hide();
        } catch (error) { }
        modal.current.stop();
    }

    /**
     * 修改教师信息
     * @param {*} values 
     */
    const updateTeacher = async values => {
        try {
            mf.current.start();
            await (teacher.id ? UpdateTeacher : AddTeacher)({ id: teacher.id, ...values });
            setSearchModel({ ...searchModel });
            mf.current.hide();
        } catch (error) { }
        mf.current.stop();
    }

    /**
     * 修改状态
     * @param {*} row 
     */
    const updateStatus = async values => {
        try {
            statusMF.current.start();
            await UpdateStatus({ id: teacher.id, status: !teacher.status, date: dayjs(values.date).format('YYYY-MM-DD HH:mm:ss') });
            setSearchModel({ ...searchModel });
            statusMF.current.hide();
        } catch (error) { }
        statusMF.current.stop();
    }

    /**
     * 更改教师角色
     * @param {*} values 角色ID
     */
    const changeRoles = async ({ roleIds }) => {
        try {
            roleMF.current.start();
            await ChangeRoles({ teacherId: teacher.id, roleIds });
            setSearchModel({ ...searchModel });
            roleMF.current.hide();
        } catch (error) { }
        roleMF.current.stop();
    }

    /**
     * 打开更改教师角色窗体
     */
    const openChangeRoles = async teacher => {
        try {
            setTeacher({ ...teacher });
            roleMF.current.show();
            const roleIds = await getTeacherRoles(teacher.id);
            setRoleValues({ roleIds });
        } catch (error) { }
    }

    return <div>
        <h3>教师列表</h3>
        <hr />
        {menuStore.auth('teacherList', 'addTeacher') && <Form values={{ subject: 0 }} options={options} attrs={{ layout: 'inline' }} onFinish={value => setSearchModel({ ...searchModel, ...value, pageNo: 1 })}></Form>}
        <p></p>
        {menuStore.auth('teacherList') && <Table cols={cols} data={list} loading={loading} page={searchModel} total={total} onChange={setSearchModel}></Table>}
        {menuStore.auth('updateTeacherPassword') && <Modal title="修改密码" ref={modal} onOk={() => form.current.submit()}>
            <Form onFinish={updatePassword} ref={form} options={passwordOptions} attrs={{ labelCol: { style: { width: 80 } } }} />
        </Modal>}
        {menuStore.auth('addTeacher', 'updateTeacher') && <MF title={teacher.id ? '修改基本信息' : '添加教师'} onFinish={updateTeacher} options={updateOptions} ref={mf} values={teacher} formAttrs={{ labelCol: { style: { width: 80 } } }}></MF>}
        {menuStore.auth('changeTeacherStatus') && <MF ref={statusMF} onFinish={updateStatus} title="修改教师状态" options={{
            date: {
                title: '日期',
                tag: 'date',
                required: true
            }
        }} />}
        {menuStore.all('teacherList', 'addTeacherRoles') && <MF onFinish={changeRoles} title="修改教师角色" options={roleOptions} ref={roleMF} values={roleValues} />}
    </div >
}